package dao

import (
	"asuOfficialApi/comm"
	"asuOfficialApi/model"
	"github.com/go-xorm/xorm"
	"log"
)

type UserDao struct {
	engine *xorm.Engine
}

func NewUserDao(engine *xorm.Engine) *UserDao {
	return &UserDao{
		engine: engine,
	}
}

func (d *UserDao) FindById(id int64) *model.User {
	data := &model.User{Id: id}
	ok, err := d.engine.Get(data)
	if err != nil {
		log.Fatal("UserDao.FindById 数据库查询错误")
	}

	if ok {
		return data
	} else {
		return nil
	}
}

func (d *UserDao) CheckExist(username string) bool {
	data := &model.User{Username: username}
	ok, err := d.engine.Get(data)
	if err != nil {
		log.Fatal("UserDao.CheckExist 数据库查询错误")
	}

	if ok {
		return true
	} else {
		return false
	}
}

func (d *UserDao) InsertUser(username, password string) *model.User {
	data := &model.User{Username: username, Password: comm.CreateSign(password)}
	if _, err := d.engine.InsertOne(data); err != nil {
		log.Fatal("UserDao.InsertUser 数据库插入错误")
		return nil
	} else {
		return data
	}
}

func (d *UserDao) CheckAccount(username, password string) *model.User {
	user := &model.User{Username: username, Password: comm.CreateSign(password)}
	ok, err := d.engine.Get(user)
	if err != nil {
		log.Fatal("UserDao.CheckAccount 数据库查询错误")
	}

	if ok {
		return user
	} else {
		return nil
	}
}
